package com.kun.hanlp.listener;

import com.kun.hanlp.config.HanlpProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author kun.li
 */
@Slf4j
public class HanlpListener implements ApplicationListener<ContextRefreshedEvent> {
    private HanlpProperties hanlpProperties;

    @Autowired
    public void setHanlpProperties(HanlpProperties hanlpProperties) {
        this.hanlpProperties = hanlpProperties;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        startFileWatch();
    }

    private AtomicBoolean first  =new AtomicBoolean(false);

    private void startFileWatch() {

        if (first.getAndSet(true)) {
            return;
        }

        //Interval time 5 seconds(间隔时间5秒)
        long intervalTime = TimeUnit.SECONDS.toMillis(hanlpProperties.getWatchFileTime());

        FileAlterationObserver observer = new FileAlterationObserver(
                hanlpProperties.getWatchFileDirPath(),
                FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
                        FileFilterUtils.prefixFileFilter(hanlpProperties.getWatchFilePrefix()),
                        FileFilterUtils.suffixFileFilter(hanlpProperties.getWatchFileSuffix())));
        //设置文件改变监听器
        observer.addListener(new HanlpFileListener());
        // 创建文件该表监视器
        FileAlterationMonitor command = new FileAlterationMonitor(intervalTime, observer);

        try {
            // 设置线程工厂
            CustomizableThreadFactory customizableThreadFactory = new CustomizableThreadFactory();
            customizableThreadFactory.setThreadNamePrefix("hanlpFileWatch-");
            command.setThreadFactory(customizableThreadFactory);
            //启动监视器
            command.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
